package com.xu.base.utils;

import com.xu.base.tree.ITreeNode;

import java.util.*;

/**
 * @Description: 菜单树工具类 需要实现ITreeNode接口后才能使用
 *
 * @Author: 许乾伟
 * @Date: 2023/9/13  16:20
 */
public class TreeNodeUtils {

    /**
     * 构建一棵树
     *
     * @param nodeList 节点列表
     * @param <T>      实现ITreeNode接口的节点类型
     * @return 根节点列表
     */
    public static <T extends ITreeNode> List<T> buildTree(List<T> nodeList) {
        if (nodeList == null || nodeList.isEmpty()) {
            return Collections.emptyList();
        }

        Map<Object, T> idNodeMap = new HashMap<>();
        Map<Object, List<T>> parentIdChildrenMap = new HashMap<>();
        Object rootId = null;
        for (T node : nodeList) {
            idNodeMap.put(node.getNodeId(), node);
            //获取父节点和子节点map
            parentIdChildrenMap.computeIfAbsent(node.getParentNodeId(), k -> new ArrayList<>()).add(node);
            if (node.isRoot()) {
                //获取根节点
                rootId = node.getParentNodeId();
            }
        }
        List<T> rootNodes = new ArrayList<>();
        for (Map.Entry<Object, List<T>> entry : parentIdChildrenMap.entrySet()) {
            Object parentId = entry.getKey();
            List<T> children = entry.getValue();
            if (parentId.equals(rootId)) {
                rootNodes.addAll(children);
            }
            T parentNode = idNodeMap.get(parentId);
            if (parentNode != null) {
                parentNode.setChildren(children);
            }
        }
        return rootNodes;
    }
}
